package com.bluesky.drcp.business.service;

import java.util.List;
import java.util.StringTokenizer;

import com.bluesky.drcp.business.Function;
import com.bluesky.drcp.persistence.dao.FunctionDao;

public class FunctionService {
	private FunctionDao functionDao;

	public FunctionDao getFunctionDao() {
		return functionDao;
	}

	public void setFunctionDao(FunctionDao functonDao) {
		this.functionDao = functonDao;
	}

	public Function get(String id) {
		return functionDao.get(id);
	}

	public Function getRoot() {
		return functionDao.getRoot();
	}

	public Function getParent(String id) {
		try {
			Function c = functionDao.get(id);
			Function p = functionDao.get(c.getParentId());
			return p;
		} catch (Exception e) {
			return null;
		}

	}

	public List getChildren(String id) {
		return functionDao.getChildren(id);
	}

	public String getPath(String id) {
		Function o;
		o = functionDao.get(id);
		String path = "";
		while (o != null) {
			path = "\\" + o.getName() + path;
			o = getParent(o.getId());
		}

		return path.substring(1, path.length());
	}

	/**
	 * 
	 * @param baseId
	 * @param relativePath ,
	 *            not start with \
	 * @return
	 */
	public Function getByPath(String baseId, String relativePath) {
		StringTokenizer st = new StringTokenizer(relativePath, "\\");
		Function o = functionDao.get(baseId);
		String curId = null;
		while (st.hasMoreElements()) {
			curId = o.getId();
			String path = (String) st.nextElement();
			o = functionDao.getByParentIdAndName(curId, path);
			if (o == null)
				return null;
		}

		return o;
	}

	public Function getByPath(String path) {
		return getByPath("\\", path.substring(2, path.length()));
	}

	public List getAll(){
		return functionDao.getAll();
	}
	
	public void delete(String id){
		functionDao.delete(id);
	}
	
	public String save(Function function){
		return functionDao.save(function);
	}
	
	public void update(Function function){
		functionDao.update(function);
	}
	
}
